class Solution {
public:
    int dir[4][2] = {
        {-1, 0}, {1, 0}, {0, -1}, {0, 1}
    };
    void dfs(vector<vector<char>> &grid, int x, int y) {
        grid[x][y] = '2';
        for (int k = 0; k < 4; k++) {
            int dx = x + dir[k][0], dy = y + dir[k][1];
            if (dx < 0 || dx >= grid.size() || dy < 0 || dy >= grid[0].size()) continue;
            if (grid[dx][dy] != '1') continue;
            dfs(grid, dx, dy);
        }
        return ;
    }
    int numIslands(vector<vector<char>>& grid) {
        int m = grid.size(), n = grid[0].size();
        int cnt = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] != '1') continue;
                ++cnt;
                dfs(grid, i, j);
            }
        }
        return cnt;
    }
};
